package com.sicheng.metadata;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/5/8 21:04
 */
public class 负载均衡轮询算法 {
    //CAS 与 自旋锁
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    public final int getAndIncrement() {
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = (current + 1) % Integer.MAX_VALUE;
        } while (!this.atomicInteger.compareAndSet(current, next));
        System.out.println("**********第几次访问次数next:" + next);
        return next;
    }

    //获取请求负载到的实例
    public Object getInstance(List<Object> instances) {
        int index = getAndIncrement() & (instances.size() - 1);
        return instances.get(index);
    }
}
